package com.rjkj.medicalwaste.ui.storage

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.adapter.*
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.base.showTip
import com.rjkj.medicalwaste.bean.*
import com.rjkj.medicalwaste.database.GarbageSetBoxed
import com.rjkj.medicalwaste.databinding.FragmentBoxListBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.Encoder03Small
import com.rjkj.medicalwaste.utils.StringUtils
import com.rjkj.medicalwaste.utils.TimeUtils
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.BoxListViewModel
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.launch
import java.math.BigDecimal

class BoxListFragment : BaseFragment<FragmentBoxListBinding>() {
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()

    private val unBoxedViewModel: UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }
    private val boxListViewModel: BoxListViewModel by activityViewModels()
    private val tempBoxListAdapter: TempBoxListAdapter by lazy {
        TempBoxListAdapter(
            requireContext(),
            object : ItemClick<GarbageInTempBoxBean> {
                override fun onClicked(view: View, value: GarbageInTempBoxBean) {
                    if (userViewModel.setting.value?.fixedBoxCode == true) {
                        val scanFixedBoxDialog = ScanFixedBoxDialog()
                        scanFixedBoxDialog.setStyle(
                            DialogFragment.STYLE_NORMAL,
                            R.style.dialogNormal
                        )//添加上面创建的style
                        scanFixedBoxDialog.show(parentFragmentManager, "ScanFixedBoxDialog")
                        boxListViewModel.openScanFixBoxDialog = true
                        scanFixedBoxDialog.callBack = object : ScanFixedBoxDialog.Callback {
                            override fun onGetCode(code: String) {
                                boxListViewModel.openScanFixBoxDialog = false
                                closeBox(value, code)

                            }
                        }

                    } else {
                        closeBox(value)
                    }

                }
            }, listOf()
        )
    }


    private val boxListAdapter: BoxListAdapter by lazy {
        val fixedBoxCode = userViewModel.setting.value?.fixedBoxCode ?: true
        BoxListAdapter(fixedBoxCode, listOf(), requireContext(),
            object : ItemClick<GarbageInBoxBean> {
                override fun onClicked(view: View, value: GarbageInBoxBean) {
                    openBox(value)
                }

            },
            object : ItemDataClick<GarbageInBoxBean> {
                override fun onClicked(value: GarbageInBoxBean) {
                    val encoder03 = Encoder03Small()
                    encoder03.setQRcode("2", value.garbageBoxQRCode, userViewModel.hospitalId.value)
                    encoder03.setGarbage(
                        userViewModel.hospitalName.value,
                        value.garbageBoxTime,
                        value.garbageBoxWeight,
                        value.garbageType.typeConfig,
                        userViewModel.cleanerUser.name,
                        value.garbageBoxTime,
                        value.garbageBoxTime
                    )
                    bluetoothControlViewModel.packingBoxTag(encoder03)
                }

            }, object : InvalidClick {
                override fun onInvalidClick(l: Long) {
                    val pi = l.div(1000)
                    showTip("请${pi}秒后再试")
                }

            })
    }
    var openBoxDialog:OpenBoxDialog? = null
    private fun openBox(value: GarbageInBoxBean) {
        Log.e(TAG, "onClicked: $value")
        if(openBoxDialog!=null){
            openBoxDialog!!.dismiss()
            openBoxDialog = null
            openBox(value)
        }else{
            val bundle = Bundle()
            bundle.putString(BOX_CODE, value.garbageBoxQRCode)
            bundle.putString(BOX_TYPE, value.garbageType.typeName)
            openBoxDialog = OpenBoxDialog().apply {
                arguments = bundle
                setStyle(
                    DialogFragment.STYLE_NORMAL,
                    R.style.dialogFullScreen
                );//添加上面创建的style
            }
            openBoxDialog!!.show(parentFragmentManager, "openDialog")
        }


    }
    companion object{
        const val BOX_CODE = "boxCode"
        const val BOX_TYPE = "boxType"
        const val GARBAGE_TYPE = "garbageCode"
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentBoxListBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }

    override fun onSubscribeUi(binding: FragmentBoxListBinding) {
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                //扫描的是固定箱码
                if(!boxListViewModel.openScanFixBoxDialog){
                    val find =
                        boxListAdapter.list.find { garbageInBoxBean -> garbageInBoxBean.garbageBoxQRCode == it.split("?").last() }
                    if (find != null) {
                        openBox(find)
                    }else {
                        showTip("未找到有效箱码")
                    }
                }//开箱
                else{
                    boxListViewModel.scanFixBoxCode.value = it
                }
            })
        binding.list.apply {
            layoutManager = LinearLayoutManager(requireContext())

            adapter = boxListAdapter
        }
        binding.list2.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = tempBoxListAdapter
        }
        binding.imBack.setOnClickListener {
            findNavController().navigateUp()
        }
        unBoxedViewModel.repository.getBoxGarbageBeanList(
            userViewModel.hospitalId.value
                ?: "", userViewModel.stagingRoomUser.value?.qrcode
                ?: ""
        ).observe(viewLifecycleOwner, { value ->
            Log.e(TAG, "onSubscribeUi: ${value.toString()}")
            if (value.isNullOrEmpty()) {
                showTip("暂无已装箱数据")
                boxListAdapter.list = listOf()
                boxListAdapter.notifyDataSetChanged()
                return@observe
            }
            val groupBy = value.groupBy { it.garbageBoxQRCode }.map { map ->
                GarbageInBoxBean(
                    garbageType = MedicalWasteType.getBoxTypeByTypeName(map.value[0].garbageType),
                    garbageBoxQRCode = map.key,
                    garbageList = map.value,
                    garbageBoxTime = map.value[0].garbageBoxTime,
                    garbageBoxWeight = map.value[0].garbageBoxWeight

                )
            }
            boxListAdapter.list = groupBy
            boxListAdapter.notifyDataSetChanged()
        })


        unBoxedViewModel.repository.getTempBoxGarbageBeanList(
            userViewModel.hospitalId.value
                ?: "", userViewModel.stagingRoomUser.value?.qrcode
                ?: ""
        ).observe(viewLifecycleOwner, { value ->
            Log.e(TAG, "onSubscribeUi: $value")
            if (value.isNullOrEmpty()) {
                showTip("暂无可装箱数据")
                tempBoxListAdapter.list = listOf()
                tempBoxListAdapter.notifyDataSetChanged()
                return@observe
            }
            val groupBy = value.groupBy { it.tempBoxQRCode }.map { map ->
                GarbageInTempBoxBean(
                    garbageType = MedicalWasteType.getTypeByTypeName(map.value[0].garbageType),
                    tempBoxQRCode = map.key,
                    garbageList = map.value
                )
            }
            tempBoxListAdapter.list = groupBy
            tempBoxListAdapter.notifyDataSetChanged()


        })

    }

    /**
     *
     * @param value GarbageInTempBoxBean
     * @param code String 固定箱码
     */
    private fun closeBox(value: GarbageInTempBoxBean, code: String = "") {
        lifecycleScope.launch {
            val sQRCodetime = TimeUtils.getTimeStr() //二维码时间
            if (unBoxedViewModel.time == sQRCodetime) {
                showTip("请稍后再试")
                return@launch
            } else {
                unBoxedViewModel.time = sQRCodetime
            }
            val size = value.garbageList.size
            val sumByDouble = value.garbageList.sumByDouble { it.garbageWeight.toDouble() }
            val boxCleanerQRCode = userViewModel.cleanerUser.qrcode
            val garbageBoxQRCode: String = if (code.isEmpty()) {
                "2${userViewModel.getSerial()}$sQRCodetime"
            } else {
                code
            } //生成垃圾箱二维码
            val map = value.garbageList.map { garbage ->
                val time = TimeUtils.getYMDHMSTime()
                GarbageSetBoxed(
                    id = garbage.id,
                    garbageCNT = size,
                    garbageUserStatus = GarbageStatus.boxed,
                    garbageQRCode = garbage.garbageQRCode,
                    garbageBoxQRCode = garbageBoxQRCode,
                    garbageBoxDeviceSN = userViewModel.getSerial(),
                    garbageBoxTime = time,
                    garbageBoxType = MedicalWasteType.getTypeByTypeName(garbage.garbageType).typeConfig,
                    garbageBoxWeight = BigDecimal(sumByDouble).setScale(2, BigDecimal.ROUND_HALF_UP)
                        .toString(),
                    boxCleanerQRCode = boxCleanerQRCode,
                )
            }
            unBoxedViewModel.updateGarbageSetBoxed(*map.toTypedArray())
            printBoxTag(garbageBoxQRCode, value)
            for (garbageSetBoxed in map) {
                val findGarbageByCode2 =
                    unBoxedViewModel.repository.findGarbageByCode2(garbageSetBoxed.garbageQRCode)
                if (findGarbageByCode2 != null) {
                    userViewModel.uploadGarbage(
                        garbageBeanList = arrayListOf(findGarbageByCode2),
                        successState = GarbageBean.boxState,
                        failState = GarbageBean.nullState,
                    )
                }
            }
            Log.e(TAG, "closeBox: finish")

        }

    }

    private fun printBoxTag(
        garbageBoxQRCode: String,
        value: GarbageInTempBoxBean
    ) {
        if (userViewModel.setting.value?.fixedBoxCode == false) {
            val sYMD = TimeUtils.getYMDHMSTime() //当前年月日
            val encoder03 = Encoder03Small()
            encoder03.setQRcode("2", garbageBoxQRCode, userViewModel.hospitalId.value)
            encoder03.setGarbage(
                userViewModel.hospitalName.value,
                sYMD,
                "0.00",
                value.garbageType.typeConfig,
                userViewModel.cleanerUser.name,
                sYMD,
                sYMD
            )
            bluetoothControlViewModel.packingBoxTag(encoder03)
        }
    }

}